<?php

namespace app\common\model;

use think\Model;

/**
 * 田园鲜仓总模型父类
 */
class Base extends Model {
	public $aliasName = '';
	protected $isPrivacy = false;
	protected $privacyFields   = [];

	// 重写 alias 方法
    public function alias($alias)
    {
        $this->aliasName = $alias;
        return parent::alias($alias);
    }

	//设置隐私
	public function privacy($with = null) {
		 $this->isPrivacy = true;
		 $this->hidden = array_merge((array)$this->hidden, $this->privacyFields);
		 if(is_array($with)) {
		 	foreach ($with as $k => $closure) {
		 		if(!is_string($closure)) {
		 			$this[$k]->privacy();
		 		} else {
		 			$this[$closure]->privacy();
		 		}
		 		
		 	}
		 }
		 return $this;
	}

	//获取模型隐私字段
	public function getModelAttr($key) {
		return $this->$key;
	}

	//删除隐私字段
	public function removePrivacyField($value) {
		$this->privacyFields = array_diff($this->privacyFields, [$value]);
		return $this;
	}

	//修改隐私字段
	public function setPrivacyFields($privacyFields) {
		$this->privacyFields = $privacyFields;
		return $this;
	}

	//返回隐私字段
	public function getPrivacyFields() {
		return $this->privacyFields;
	}

	public static function factory() {
		return new static();
	}

	public function order(...$args) {
		parent::order(...$args);
		return $this;
	}

	public function append($append = [], $override = false) {
		if(is_string($append)) {
			$append = [$append];
		}
		return parent::append($append, $override);
	}

	public function select(...$args) {
		$list = parent::select(...$args);
		$isPrivacy = $this->isPrivacy;
		$privacyFields = $this->getPrivacyFields();
		$isAppend = count($this->append) > 0;
		if($isAppend || $isPrivacy) {
			foreach ($list as $key => $value) {
				if($isPrivacy) {
					$value->setPrivacyFields($privacyFields);
					$value->privacy();
				}
				if($isAppend) {
					$value->append($this->append);
				}
			}
		}
		return $list;
	}

	public function paginate(...$args) {
		$list = parent::paginate(...$args);
		$isPrivacy = $this->isPrivacy;
		$privacyFields = $this->getPrivacyFields();
		$isAppend = count($this->append) > 0;
		if($isAppend || $isPrivacy) {
			foreach ($list as $key => $value) {
				if($isPrivacy) {
					$value->setPrivacyFields($privacyFields);
					$value->privacy();
				}
				if($isAppend) {
					$value->append($this->append);
				}
			}
		}
		return $list;
	}

	public function __call($method, $args) {
		if($method == 'where') {
			$query = $this->db(true, false);
			call_user_func_array([$query, $method], $args);
			return $this;
		}
		return parent::__call($method, $args);
	}	
}